package cn.com.twoke.game.client.games.framework.ui;

import cn.com.twoke.game.client.games.framework.core.Game;

import javax.swing.*;
import java.awt.*;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

public class MessageListJPanel extends JPanel {
        private List<ChatMessage> messages = new ArrayList<>();
        private SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        private Game game;
        public MessageListJPanel(Game game, List<ChatMessage> messages) {
            this.game = game;
            this.messages = messages;
        }

        public void addMessage(ChatMessage message) {
            this.messages.add(message);
            this.repaint();
        }


        @Override
        protected void paintComponent(Graphics g) {
            super.paintComponent(g);
            Graphics2D g2d = (Graphics2D) g;
            // 抗锯齿
            g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
            if (null == this.messages) return;
            int y = 10;
            int x = 5;
            FontMetrics fontMetric;
            for (ChatMessage message : this.messages) {
                g2d.setFont(new Font("微软雅黑", Font.PLAIN, 10));
                g2d.drawString(sdf.format(new Date(message.time)), x, y);
                y += 15;
                Color color = g2d.getColor();
                if (message.fromId.equals(this.game.getPlayerName())) {
                    g2d.setColor(Color.RED);
                }
                g2d.setFont(new Font("微软雅黑", Font.BOLD, 12));
                g2d.drawString(message.fromId, x, y);
                g2d.setColor(color);
                y += 20;;
                g2d.setFont(new Font("微软雅黑", Font.ITALIC, 14));
                fontMetric = g2d.getFontMetrics();
                String line = "", word = "";
                for (int i = 0; i < message.content.length(); i++) {
                    word = String.valueOf(message.content.charAt(i));
                    line += word;
                    int lineWidth = fontMetric.stringWidth(line);
                    if (lineWidth >= 220) {
                        g2d.drawString(line, x, y);
                        y += fontMetric.getHeight();
                        line = "";
                    }
                }
                if (line.length() > 0) {
                    g2d.drawString(line, x, y);
                }

                y += 30;
            }

            this.setPreferredSize(new Dimension(240, y));
            this.revalidate();
        }
    }

